package com.hlbspringcloud.springbootquartz.service.impl;

import com.hlbspringcloud.springbootquartz.job.HelloJob;
import com.hlbspringcloud.springbootquartz.service.QuartzService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author huanglibin
 * @Project spring-boot-quartz
 * @Description
 * @Date 2020-07-06-15-45-11
 * @Version 1.0
 */
@Slf4j
@Service
public class QuartzServiceImpl implements QuartzService {

    @Autowired
    private Scheduler scheduler;
    
    /**
     * 新增一个定时任务
     * @param jName 任务名称
     * @param jGroup 任务组
     * @param tName 触发器名称
     * @param tGroup 触发器组
     * @param cron cron表达式
     */
    @Override
    public void addJob(String jName, String jGroup, String tName, String tGroup, String cron) {
        try {
            JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity(jName,jGroup).build();
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(tName,tGroup).startNow().withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
            scheduler.start();
            scheduler.scheduleJob(jobDetail,trigger);
        }catch (Exception e){
            log.error("新增定时任务失败,异常为:{}",e);
        }
    }

    /**
     * 暂停定时任务
     * @param jName 任务名
     * @param jGroup 任务组
     */
    @Override
    public void pauseJob(String jName, String jGroup) {
        try {
            scheduler.pauseJob(JobKey.jobKey(jName,jGroup));
        }catch (Exception e){
            log.error("暂停定时任务失败,异常为:{}",e);
        }
    }

    /**
     * 继续定时任务
     * @param jName 任务名
     * @param jGroup 任务组
     */
    @Override
    public void resumeJob(String jName, String jGroup) {
        try {
            scheduler.resumeJob(JobKey.jobKey(jName, jGroup));
        }catch (Exception e){
            log.error("重启定时任务失败,异常为:{}",e);
        }
    }

    /**
     * 删除定时任务
     * @param jName 任务名
     * @param jGroup 任务组
     */
    @Override
    public void deleteJob(String jName, String jGroup) {
        try {
            scheduler.deleteJob(JobKey.jobKey(jName, jGroup));
        }catch (Exception e){
            log.error("删除定时任务失败,异常为:{}",e);
        }
    }
}
